﻿using System;
using System.IO;
using System.Linq;
using Wicresoft.Logger;
using Wicresoft.Task.Common;
using Wicresoft.Task.Team.Entity;

namespace Wicresoft.Task.Team
{
    class Nofitier
    {
        TfsAutoNotifyContext tfsDB = new TfsAutoNotifyContext();
        private string website;
        private string CC;


        public Nofitier(string Website,string cc)
        {
            this.website = Website;
            this.CC = cc;
        }
        public EmailTemplate CreateEmail(ShelveInfo s)
        {
            EmailTemplate email = new EmailTemplate();
            using (TfsAutoNotifyContext TeamDB = new TfsAutoNotifyContext())
            {
                string tempBody = Helper.ReadFile("Body.html");
                var itemStr = tfsDB.WorkItemInfoes.Where(p => p.ShelvesetId == s.ShelvesetId).ToArray();
                string workItemInfor = Helper.ReturnWorkItemInfo(itemStr, TeamDB, s);
                string codeReviewer = s.CodeReviewer;
                string mailTo = QueryMailTo(codeReviewer, tfsDB);
                string manager = QueryManager(s.AreaId, TeamDB);
                if (s.WorkItemInfoes.First().WorkItemId == -1||s.AreaId==-1)
                {
                    Log.Info("Email To", " You Don't Binging The Work Item ");
                    email = null;
                    var emp = tfsDB.EmployeesInfoes.FirstOrDefault(p => s.OwnerName.Contains(p.AD4Alias));
                    string errorEmail = emp.Email;
                    string name = emp.EnglishName;
                    string bod = Helper.ReadFile("InvalidCodeReview.html");
                    string body = string.Format(bod, name, "You Don't Binging The Work Item" + "<Br/> You Should Delete The Invalid Shelve And Then Reshelve.Thanks!");
                    SmtpHelper.SendEmail(" You Don't Binging The Work Item Or You don't Select the WorkItem's Area", body, "noreply@ws-fs-01.local",new string[] {errorEmail}, manager.Split(new char[] {';'}));
                }
                else 
                {
                    if (mailTo == "")
                    {
                        Log.Info("Email To", " You Type A Invalid Code Reviewer");
                        email = null;
                        var emp = tfsDB.EmployeesInfoes.FirstOrDefault(p => s.OwnerName.Contains(p.AD4Alias));
                        string errorEmail = emp.Email;
                        string name = emp.EnglishName;
                        string bod = Helper.ReadFile("InvalidCodeReview.html");
                        string body = string.Format(bod, name, "You Type A Invailid Code Reviewer:" + codeReviewer + "<Br/> You Should Delete The Invalid Shelve And Then Reshelve.Thanks!");
                        SmtpHelper.SendEmail("You Type A Invailid Code Reviewer:" + codeReviewer, body, "noreply@ws-fs-01.local", new string[] { errorEmail }, manager.Split(new char[] { ';' }));
                    }
                    else
                    {
                        if (s.AreaId == -2)
                        {
                            SmtpHelper.SendEmail(s.WorkItemInfoes.First().Area + "don't have the manager", s.WorkItemInfoes.First().Area + "don't have the manager", "ws-fs-01@noreplay.com", "i-jibw@wicresoft.com");

                        }
                        {
                            string codeReviewerEnglishName = TeamDB.EmployeesInfoes.First(p => p.Email == mailTo).EnglishName;
                            string body = string.Format(tempBody, s.OwnerName.TrimStart(), workItemInfor.TrimStart(), s.Comment.TrimStart());
                            email.Bcc = "i-jibw@wicresoft.com";
                            email.Body = body;
                            Employee _Es = TeamDB.EmployeesInfoes.First(p => s.OwnerName.ToLower().Contains(p.AD4Alias.ToLower()));
                            email.Cc = manager;
                            email.CreatedTime = DateTime.Now;
                            email.From = "noreply@ws-fs-01.local";
                            email.ReplyTo = _Es.Email;
                            email.Subject = "Code review request: " + s.Name;
                            email.To = mailTo;
                        }
                    }
                }
            }
            return email;
        }
        public string QueryMailTo(string codeReviewer, TfsAutoNotifyContext TeamDB)
        {
            string email = "";

            var employeesInfo = TeamDB.EmployeesInfoes.ToList();
            foreach (var x in employeesInfo)
            {
                if (codeReviewer.Trim().Length != 0)
                {
                    if (IsWho(x, codeReviewer))
                    {
                        email = x.Email;
                    }
                }
            }
            return email;

        }
        public string QueryManager(int areaId, TfsAutoNotifyContext TeamDB)
        {
            string email = "";
            string managers = "";
            try
            {
                managers = tfsDB.Areas.First(p => p.AreaId == areaId).WSAlias;
            }
            catch (Exception e)
            {
                managers = "";
            }
            if (managers != "")
            {
                if (managers.Contains(";") || managers.Contains(","))
                {
                    string[] x = managers.Split(new char[] { ';', ',' });
                    for (int i = 0; i < x.Length; i++)
                    {
                        string item = x[i];
                        if (i == x.Length - 1)
                        {
                            email = email + QueryMailTo(item, tfsDB);
                        }
                        else
                        {
                            email = email + QueryMailTo(item, tfsDB) + ";";
                        }
                    }
                }
                else
                {
                    email = QueryMailTo(managers, tfsDB);
                }
            }
            else
            {
                email = "";
            }
            return email;
        }
        public bool IsWho(Employee p, string codeReviewers)
        {
            bool x = false;

            string codeReviewer = codeReviewers.Trim();
            if (p.Name.Trim().Contains(codeReviewer))
            {
                x = true;
            }

            //if (p.EnglishName.Trim().Equals(codeReviewer, StringComparison.OrdinalIgnoreCase))
            //{
            //    x = true;
            //}
            //if (p.Pinyin.Trim().ToLower().Contains(codeReviewer.ToLower()))
            //{
            //    x = true;
            //}

            if (p.WSAlias.Trim().ToUpper().Contains(codeReviewer.ToUpper()))
            {
                x = true;

            }
            if (p.AD4Alias.Trim().ToUpper().Contains(codeReviewer.ToUpper()))
            {
                x = true;

            }
            return x;
        }
    }
}
